package com.sai.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.sai.common.api.vo.Result;
import com.sai.common.constant.CacheConstant;
import com.sai.common.constant.CommonConstant;
import com.sai.common.system.api.ISysBaseAPI;
import com.sai.common.system.util.JwtUtil;
import com.sai.common.system.vo.LoginUser;
import com.sai.common.utils.*;
import com.sai.system.entity.SysDepart;
import com.sai.system.entity.SysUser;
import com.sai.system.model.SysLoginModel;
import com.sai.system.service.ISysDepartService;
import com.sai.system.service.ISysUserService;
import com.sai.system.shiro.vo.DefContants;
import com.sai.system.util.RandImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;

@RestController
@RequestMapping("/sys")
@Slf4j
public class LoginController {
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
    private RedisUtil redisUtil;
	@Autowired
	private ISysDepartService sysDepartService;

	private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Result login(@RequestBody SysLoginModel sysLoginModel){
		String username = sysLoginModel.getUsername();
		String password = sysLoginModel.getPassword();
        String captcha = sysLoginModel.getCaptcha();
        if(captcha==null){
			return Result.error500("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
		String realKey = MD5Util.MD5Encode(lowerCaseCaptcha+sysLoginModel.getCheckKey(), "utf-8");
		Object checkCode = redisUtil.get(realKey);
		if(checkCode==null || !checkCode.equals(lowerCaseCaptcha)) {
			return Result.error500("验证码错误");
		}

		//1. 校验用户是否有效
		SysUser sysUser = sysUserService.getUserByName(username);
		Result result = sysUserService.checkUserIsEffective(sysUser);
		if(!result.isSuccess()) {
			return result;
		}
		
		//2. 校验用户名或密码是否正确
		String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
		String syspassword = sysUser.getPassword();
		if (!syspassword.equals(userpassword)) {
			return Result.error500("用户名或密码错误");
		}
				
		//用户登录信息
		userInfo(sysUser, result);
		sysBaseAPI.addLog("用户名: " + username + ",登录成功！", CommonConstant.LOG_TYPE_1, null);

		return result;
	}

	/**
	 * 退出登录
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
		//用户退出逻辑
		String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
		if (ConvertUtils.isEmpty(token)) {
			return Result.error("退出登录失败！");
		}
		String username = JwtUtil.getUsername(token);
		LoginUser sysUser = sysBaseAPI.getUserByName(username);
		if (sysUser != null) {
			sysBaseAPI.addLog("用户名: " + sysUser.getRealname() + ",退出成功！", CommonConstant.LOG_TYPE_1, null);
			log.info(" 用户名:  " + sysUser.getRealname() + ",退出成功！ ");
			//清空用户登录Token缓存
			redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
			//清空用户登录Shiro权限缓存
			redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
			//清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
			redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
			//调用shiro的logout
			SecurityUtils.getSubject().logout();
			return Result.ok("退出登录成功！");
		} else {
			return Result.error("Token无效!");
		}
	}

	/**
	 * 用户信息
	 *
	 * @param sysUser
	 * @param result
	 * @return
	 */
	private Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {
		String syspassword = sysUser.getPassword();
		String username = sysUser.getUsername();
		// 生成token
		String token = JwtUtil.sign(username, syspassword);
		// 设置token缓存有效时间
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);

		// 获取用户部门信息
		JSONObject obj = new JSONObject();
		List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
		if (departs.size() == 1) {
			sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
		}
		obj.put("token", token);
		obj.put("userInfo", sysUser);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}

	/**
	 * 后台生成图形验证码
	 *
	 * @param response
	 * @param key
	 */
	@GetMapping(value = "/randomImage/{key}")
	public void randomImage(HttpServletResponse response, @PathVariable String key) {
//		Result<String> res = new Result<String>();
		try {
			String code = RandomUtil.randomString(BASE_CHECK_CODES, 4);
			String lowerCaseCode = code.toLowerCase();
			String realKey = MD5Util.MD5Encode(lowerCaseCode + key, "utf-8");
			redisUtil.set(realKey, lowerCaseCode, 60);
			RandomCodeUtil randomCodeUtil = new RandomCodeUtil();
			randomCodeUtil.generateCaptcha(code, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}